package club.beimeng.Sender1;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HandOut {
    Session session ; // 普通qq
    Queue<MimeMessage> queue = new LinkedList<MimeMessage>(); // 全局队列
    boolean threadRunning = false;
    ExecutorService threadPool = Executors.newFixedThreadPool(10);
    Prop users;

    {// 初始化代码块
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");  //设置QQ邮件服务器 smtp.exmail.qq.com
        prop.setProperty("mail.transport.protocol", "smtp");  // 邮件发送协议

        // 关于QQ邮箱，还要设置SSL加密，加上以下代码即可
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        session = Session.getDefaultInstance(prop);
        users = new Prop();
    }



    public boolean receiveTask(BEmail bEmail){ // 接收任务函数
        MimeMessage message = new MimeMessage(session); // 创建邮件对象
//        message.setFrom();// 这个将在发送邮件函数中配置
        try {
            message.setRecipients(Message.RecipientType.TO,bEmail.getInternetAddresses()); // 配置收件人
            message.setSubject(bEmail.getSubject()); // 配置标题
            message.setContent(bEmail.getMimeMultipart()); // 配置内容
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        queue.offer(message);
        if (!threadRunning){
            threadRunning = true;
            new Thread(new PlanningTask()).start();
        }
        return true;
    }

    class SolveTask implements Runnable{
        MimeMessage[] taskMessages;

        public SolveTask(MimeMessage[] taskMessages){ // 写下构造方法
            System.out.println("创建了新的线程" + new Date());

            this.taskMessages = taskMessages;
        }

        @Override
        public void run() {
            for (MimeMessage taskMessage : taskMessages) { // 使用新线程发送邮件
                sendEmail(taskMessage);
            }
        }
    }

    class PlanningTask implements Runnable{ // 规划任务线程

        @Override
        public void run() {
            System.out.println(" 默认发件线程开启 ");
            while (threadRunning){
                MimeMessage message = queue.poll();
                if (message == null)
                    continue;
                boolean b = sendEmail(message);

                if (b)
                    System.out.println("默认线程发送成功");

                try {
                    Thread.sleep(1000); // 等待一秒钟
                    if (queue.size() > 4) {
                        MimeMessage[] mimeMessages = new MimeMessage[3];
                        for (int i = 0; i < 3; i++) {
                            mimeMessages[i] = queue.poll();
                        }
                        threadPool.submit(new SolveTask(mimeMessages));// 将三个任务分配给新线程
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean sendEmail(MimeMessage message){
        try {
            Transport ts = session.getTransport(); //通过session得到transport对象,用它装载Message(邮件本体对象)
            String[] emailN = users.getSender(); // TODO 需要更改的地方
            String emNumber = emailN[0];
            String emCode = emailN[1];

            ts.connect("smtp.qq.com",emNumber,emCode);
            message.setFrom(new InternetAddress(emailN[0]));
            ts.sendMessage(message, message.getAllRecipients()); // 发送邮件
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void main(String[] args) throws MessagingException {
        HandOut send = new HandOut();
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封邮件正文带图片<img src='cid:2021-03-12.png'>的邮件", "text/html;charset=UTF-8");
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(text);

        send.receiveTask(new BEmail("你好1",mimeMultipart,new InternetAddress[]{new InternetAddress("1192384722@qq.com")}));
        send.receiveTask(new BEmail("你好2",mimeMultipart,new InternetAddress[]{new InternetAddress("1192384722@qq.com")}));
        send.receiveTask(new BEmail("你好3",mimeMultipart,new InternetAddress[]{new InternetAddress("1192384722@qq.com")}));

    }


}
